﻿/**
 * Peter
 * Created by: Peter Development Team
 *    http://peter.codeplex.com/
 * 
 * GNU General Public License version 2 (GPLv2)
 *    http://peter.codeplex.com/license
 *
 *  This code is provided on an AS IS basis, with no WARRANTIES,
 *  CONDITIONS or GUARANTEES of any kind.
 *  
 **/

using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using Peter.Common.Utilities;

namespace Peter.Common
{
   /// <summary>
   /// The template selector used for the docking manager.
   /// </summary>
   [ContentProperty ("DataTemplates")]
   public class DockTemplateSelector : DataTemplateSelector
   {
      /// <summary>
      /// Initializes a new custom template selector object.
      /// </summary>
      public DockTemplateSelector ()
      {
         this.DataTemplates = new ObservableCollection<DataTemplate> ();
      }

      /// <summary>
      /// Gets the dictionary with the available data templates.
      /// </summary>
      public ObservableCollection <DataTemplate> DataTemplates { get; set; }

      /// <summary>
      /// When overridden in a derived class, returns a
      /// <see cref="T:System.Windows.DataTemplate"/> based on custom logic.
      /// </summary>
      /// <param name="item">The data object for which to select the template.</param>
      /// <param name="container">The data-bound object.</param>
      /// <returns>Returns a <see cref="T:System.Windows.DataTemplate"/> or null. The default value is null.</returns>
      public override DataTemplate SelectTemplate (object item, DependencyObject container)
      {
         DataTemplate dt = null;
         if (item != null)
         {
            var itemType = item.GetType ();
            foreach (var dataTemplate in this.DataTemplates)
            {
               if (itemType == (Type) dataTemplate.DataType)
               {
                  dt = dataTemplate;
                  break;
               }
            }
            if (dt == null)
               dt = ViewRegistry.CreateTemplate (itemType);
         }

         return dt ?? base.SelectTemplate (item, container);
      }
   }
}
